package com.qf.Interceptor;

import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.Interceptor
 * @Description:
 * @Date 2022/10/5 15:16
 */
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if ("/login.jsp".equalsIgnoreCase(requestURI) || "/user".equalsIgnoreCase(requestURI) || "/register.jsp".equalsIgnoreCase(requestURI)) {
            return true;
        }
        Object user = request.getSession().getAttribute("user");
        Cookie[] cookies = request.getCookies();
        if (user == null && cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("user".equalsIgnoreCase(cookie.getName())) {
                    String decode = URLDecoder.decode(cookie.getValue(), "utf-8");

                    String[] split = decode.split("#");
                    User userFind = userService.findByUserAndPwd(split[0], split[1]);
                    if (userFind != null) {
                        request.getSession().setAttribute("user", userFind);
                        return true;
                    }else {
                        Cookie cookie1 = new Cookie("user", "");
                        cookie1.setMaxAge(0);
                        cookie.setPath("/");
                        response.addCookie(cookie1);
                        return true;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
